from django.http import JsonResponse
from xToolkit import xfile
import json,os,requests
from rest_framework.decorators import api_view
from buildapi.models import BuildingInfo
from guestapi.models import GuestInfo
from houseapi.models import HouseInfo
# Create your views here.


@api_view(['POST'])
def Xexcel(request):
# try:
    guest_openid = request.POST.get('guest_openid')
    data = request.FILES.get("file", None)
    data.name = 'data.xls'

    f = open(data.name,'wb')
    for line in data.chunks():
        f.write(line)
    f.close()

    path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

    excel = xfile.read('{}/data.xls'.format(path)).excel_to_dict(title=["住户名称", "合同开始日期", "合同结束日期", "住户身份证号码", "住户手机号码"])

    for i in range(len(excel)):
        if 'code' in excel:
            return JsonResponse({'ret':1,'msg':excel})
        else:
            index = excel[i]
            guest_name = index['住户名称']
            guest_date1 = index['合同开始日期']
            guest_date2 = index['合同结束日期']
            guest_nbr = index['住户身份证号码']
            guest_phone = index['住户手机号码']

            if None in excel[i]:
                return JsonResponse({'ret':1 , 'msg':"必须完整填写所有信息，请勿留空"})
            
            if GuestInfo.objects.filter(guest_openid=guest_openid,guest_name=guest_name,guest_nbr=guest_nbr).exists():
                return JsonResponse({'ret':1 , 'msg':"该住户：{} 已经存在".format(guest_name)})
            elif GuestInfo.objects.filter(guest_nbr=guest_nbr).exists():
                return JsonResponse({'ret':1 , 'msg':"该住户身份证号码：{} 已经存在".format(guest_name)})
            else:
                GuestInfo.objects.create(
                guest_name = guest_name,
                guest_openid = guest_openid,
                guest_date1 = guest_date1,
                guest_date2 = guest_date2,
                guest_nbr = guest_nbr,
                guest_phone = guest_phone,
                guest_network_price_type=2,
                guest_electric_price = 0,
                guest_water_price = 0,
                guest_price_type = 0,
                guest_electric_price_type = 0,
                guest_water_price_type = 0,
                guest_price = 0)
            
    return JsonResponse({'ret':0})

# except Exception as e:
#     return JsonResponse({
#             'ret': 1,
#             'msg': "发生异常:{}".format(e)
#         })




@api_view(['POST'])
def WXopenid(request):
    data = json.loads(request.body)
    try:
        appid = data['appid']
        secret = data['secret']
        js_code = data['js_code']
        grant_type = data['grant_type']

        response = requests.get('https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type={}'.format(appid,secret,js_code,grant_type))
        res = response.json()
        return JsonResponse(res)

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "发生异常:{}".format(e)
            })
